/**
 * 
 */
package org.thattoolkit.srvctl.apache22;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;

import org.apache.commons.configuration.tree.DefaultConfigurationNode;

/**
 * @author ulrb
 *
 */
public class ListenConfiguration extends DefaultConfigurationNode {
	private InetSocketAddress address;
	
	/**
	 * @param port
	 */
	private void setAddress(int port) {
		address = new InetSocketAddress(port);
	}
	
	/**
	 * @param name
	 * @param port
	 * @throws UnknownHostException
	 */
	private void setAddress(String name, int port) throws UnknownHostException {
		address = new InetSocketAddress(InetAddress.getByName(name), port);
	}
	
	/* (non-Javadoc)
	 * @see org.apache.commons.configuration.tree.DefaultConfigurationNode#setValue(java.lang.Object)
	 */
	@Override
	public void setValue(Object val) {
		super.setValue(val);
		if(val instanceof String) {
			try {
				String adr = ((String)val).trim();
				if(adr.matches("[0-9]+")) {
					int port = Integer.parseInt(adr);
					setAddress(port);
				}
				else if(adr.matches("([0-9]+\\.){3}[0-9]+:[0-9]+")) {
					String parts[] = adr.split(":",1);
					setAddress(parts[0], Integer.parseInt(parts[1]));
				}
				else if(adr.matches("\\[([0-9a-f]*:){5}[0-9a-f]*\\]:[0-9]+")) {
					int i;
					for(i = adr.length()-1; i >= 0 && adr.charAt(i) != ':'; i--)
						/* empty */;
					setAddress(adr.substring(0, i-1), Integer.parseInt(adr.substring(i+1)));
				}
				else if(adr.matches("[^:]+:[0-9]+")) {
					String parts[] = adr.split(":", 1);
					setAddress(parts[0], Integer.parseInt(parts[1]));
				}
			}
			catch(UnknownHostException e) {
				e.printStackTrace();
			}
 		}
	}
	
}
